package com.jams.goodox.activity.serve.meet;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hangzhou.jin.customview.LoadView;
import com.hangzhou.jin.customview.SpaceItemDecoration;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.entity.MeetRoomIntroduceBean;
import com.jams.goodox.entity.MeetTypeBean;
import com.jams.goodox.entity.PageInfo;
import com.jams.goodox.entity.resp.MeetPointResp;
import com.jams.goodox.entity.resp.MeetRoomListResp;
import com.jams.goodox.entity.resp.MeetTypeResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.DeviceUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.MaxListView;
import com.jams.goodox.widget.NoScrollGridView;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;
import com.jams.library.fresco.FrescoUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 场地预定列表页
 * Created by jams_zhen on 2017/5/8.
 */

public class MeetRoomListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @Bind(R.id.tx_meet_room)
    TextView txMeetRoom;
    @Bind(R.id.recycle_view)
    RecyclerView recycleView;
    @Bind(R.id.relative_room)
    RelativeLayout relativeRoom;
    @Bind(R.id.img_pop)
    ImageView imgPop;
    @Bind(R.id.swipeLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.loadView)
    LoadView loadView;
    @Bind(R.id.tx_hint)
    TextView tx_hint;
    @Bind(R.id.view_red)
    View view_red;
    @Bind(R.id.text_title)
    TextView textTitle;

    private List<MeetRoomIntroduceBean> meetRoomIntroduceBeanList;

    private List<MeetTypeBean> screenLst;

    private ListCommonAdapter screenAdapter;

    private BaseQuickAdapter meetRoomAdapter;

    private int typePsi = 0;//筛选选中项

    private PopupWindow popupWindow;

    private Intent in;

    private int curPage = 1;

    private MeetTypeBean chooseMeetType;//选择的场地类型实体
    private String subId;
    private String busId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_meet_room_list;
    }

    @Override
    protected void init() {
        setTitleVisibility(false);
        String title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) title = "场地预订";
        textTitle.setText(title);
        subId = getIntent().getStringExtra("subId");
        busId = getIntent().getStringExtra("busId");
        setRecycleView();

        initPopWin();
        swipeRefreshLayout.setOnRefreshListener(this);
        getMeetTypeList();
        loadView.loading();
        getMeetList(false);
        getOrderCanUse();
    }

    /**
     * 设置会议室列表
     */
    private void setRecycleView() {
        meetRoomIntroduceBeanList = new ArrayList<>();
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        meetRoomAdapter = new BaseQuickAdapter<MeetRoomIntroduceBean>(R.layout.meet_room_item, meetRoomIntroduceBeanList) {
            @Override
            protected void convert(BaseViewHolder helper, final MeetRoomIntroduceBean item) {
                helper.setText(R.id.tx_room_name, item.getRoomName());
                helper.setText(R.id.tx_room_price, item.getRoomPrice());
                helper.setText(R.id.tx_in_people, item.getCanInPeople());
                setEmptyGridAdapter((NoScrollGridView) helper.getView(R.id.empty_grid), item);
                helper.setText(R.id.tx_in_people,item.getCanInPeople());
                SimpleDraweeView img_icon=helper.getView(R.id.img_icon);
                if(item.getPicList().size()>0){
                    FrescoUtil.loadNetUrl(img_icon,item.getPicList().get(0));
                }else {
                    FrescoUtil.loadNetUrl(img_icon,"");
                }
                helper.setOnClickListener(R.id.tx_reserve, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        in = new Intent(MeetRoomListActivity.this, MeetChooseSessionActivity.class);
                        in.putExtra("id", item.getId());
                        in.putExtra("subId", subId);
                        in.putExtra("busId", busId);
                        startActivity(in);
                    }
                });
            }
        };
        meetRoomAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent in=new Intent(MeetRoomListActivity.this,MeetDetailActivity.class);
                in.putExtra("meetRoomIntroduceBean",meetRoomIntroduceBeanList.get(position));
                in.putExtra("subId", subId);
                in.putExtra("busId", busId);
                qStartActivity(in);
            }
        });
        recycleView.setAdapter(meetRoomAdapter);
        recycleView.addItemDecoration(new SpaceItemDecoration(DensityUtil.dp2px(this, 15)));
        meetRoomAdapter.setLoadingView(getLoadMoreBootView(this));
        meetRoomAdapter.setOnLoadMoreListener(this);
    }

    /**
     * 设置空余场次列表
     *
     * @param scrollGridView        空余场次布局
     * @param meetRoomIntroduceBean 场次数据
     */
    private void setEmptyGridAdapter(NoScrollGridView scrollGridView, final MeetRoomIntroduceBean meetRoomIntroduceBean) {
        ListCommonAdapter gridAdapter = new ListCommonAdapter<MeetRoomIntroduceBean.EmptyMeetDateBean>(this, meetRoomIntroduceBean.getEmptyMeetDateBeen(), R.layout.empty_meet_item) {
            @Override
            public void convert(ListCommonViewHolder helper, MeetRoomIntroduceBean.EmptyMeetDateBean item, int position) {
                helper.setText(R.id.tx_empty_time, item.getShowDate());
                TextView textView = helper.getView(R.id.tx_empty_time);
                textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
                textView.getPaint().setAntiAlias(true);//抗锯齿
            }
        };
        scrollGridView.setAdapter(gridAdapter);
        scrollGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                in = new Intent(MeetRoomListActivity.this, MeetChooseSessionActivity.class);
                in.putExtra("chooseDate", meetRoomIntroduceBean.getEmptyMeetDateBeen().get(position).getPlaceOpendate());
                in.putExtra("id", meetRoomIntroduceBean.getId());
                in.putExtra("subId", subId);
                in.putExtra("busId", busId);
                startActivity(in);
            }
        });
    }

    @OnClick({R.id.relative_room,R.id.img_back,R.id.right_relative})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.relative_room:
                if (popupWindow == null) return;
                if (!popupWindow.isShowing()) {
                    //此处修复7.0 popwinDow弹出位置错乱的问题
                    if (Build.VERSION.SDK_INT >= 24) {
                        int[] location = new int[2];
                        relativeRoom.getLocationOnScreen(location);
                        int mHeight = relativeRoom.getHeight() + location[1];
                        popupWindow.setHeight(DeviceUtils.getDisplayHeight(this) - mHeight);
                        popupWindow.showAtLocation(relativeRoom, Gravity.NO_GRAVITY, 0, mHeight);
                    } else {
                        popupWindow.showAsDropDown(relativeRoom);
                    }
                    imgPop.setImageResource(R.mipmap.drop_up_icon);
                } else {
                    popupWindow.dismiss();
                }
                break;
            case R.id.right_relative:
                qStartActivity(MeetHistoryActivity.class);
                break;
        }
    }

    /**
     * 初始化pop
     */
    private void initPopWin() {
        View view = getLayoutInflater().inflate(R.layout.list_pop_screen, null);
        MaxListView screenListView = (MaxListView) view.findViewById(R.id.screen_list);
        screenListView.setListViewHeight(getResources().getDimensionPixelOffset(R.dimen.screen_list_max_height));
        screenLst = new ArrayList<>();
        screenAdapter = new ListCommonAdapter<MeetTypeBean>(this, screenLst, R.layout.item_screen_type) {
            @Override
            public void convert(ListCommonViewHolder helper, MeetTypeBean item, int position) {
                helper.setText(R.id.tx_screen, item.getTypeName());
                helper.getView(R.id.img_check).setVisibility(item.isChooseType() ? View.VISIBLE : View.GONE);
            }
        };
        screenListView.setAdapter(screenAdapter);
        screenListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(typePsi<0||typePsi>=screenLst.size())return;//此处优化：筛选项列表若之后要实时刷新，需避免，刷新后列表越界
                screenLst.get(typePsi).setChooseType(false);
                screenLst.get(position).setChooseType(true);
                screenAdapter.notifyDataSetChanged();
                //此处：选中勾，重置数据
                typePsi = position;
                chooseMeetType = screenLst.get(position);
                txMeetRoom.setText(chooseMeetType.getTypeName());
                onRefresh();
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.view_default).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                imgPop.setImageResource(R.mipmap.drop_down_icon);
            }
        });
    }

    /**
     * 获取场地类型
     */
    private void getMeetTypeList() {
        enqueue(createCallService(ServiceService.class).getPlaceTypeList(), new RetrofitCallbackListener<MeetTypeResp>() {
            @Override
            public void onSuccess(Call<MeetTypeResp> call, MeetTypeResp result) {
                if (result.getData() != null && result.getData().size() > 0) {
                    screenLst.addAll(result.getData());
                    screenLst.get(0).setChooseType(true);
                    chooseMeetType = screenLst.get(0);
                    txMeetRoom.setText(chooseMeetType.getTypeName());
                    screenAdapter.notifyDataSetChanged();
                } else {
                    relativeRoom.setVisibility(View.GONE);
                    tx_hint.setVisibility(View.GONE);
                    loadView.loadCompleteNoData(R.mipmap.holder_no_meet_place,"场地预订尚未开启，请关注");
                    swipeRefreshLayout.setEnabled(false);
                }
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
            }
        });

    }

    /**
     * 获取场地预定列表
     */
    private void getMeetList(boolean isLoadMore) {
        Map<String, String> params = Constant.getPagerParams(isLoadMore ? curPage + 1 : curPage);
        if (chooseMeetType != null) params.put("placeTypeId", chooseMeetType.getPlaceTypeId());
        enqueue(createCallService(ServiceService.class).getPlaceList(params), new RetrofitCallbackListener<MeetRoomListResp>() {
            @Override
            public void onSuccess(Call<MeetRoomListResp> call, MeetRoomListResp result) {
                if (relativeRoom.getVisibility() == View.GONE) {
                    loadView.loadCompleteNoData(R.mipmap.holder_no_meet_place,"场地预订尚未开启，请关注");
                    return;
                }
                loadView.loadComplete();
                swipeRefreshLayout.setRefreshing(false);
                if (result.getData() == null || result.getData().getResultList() == null || result.getData().getPageInfo() == null) {
                    if (meetRoomIntroduceBeanList.size() == 0) loadView.loadCompleteNoData(R.mipmap.holder_no_meet_place,"暂无场地呐.....");
                    meetRoomAdapter.notifyDataChangedAfterLoadMore(false);
                    return;
                }
                PageInfo pageInfo = result.getData().getPageInfo();
                if (curPage == 1) meetRoomIntroduceBeanList.clear();
                meetRoomIntroduceBeanList.addAll(result.getData().transform());
                curPage = pageInfo.getCurPage();
                meetRoomAdapter.notifyDataChangedAfterLoadMore(pageInfo.isHasMore());
                if (meetRoomIntroduceBeanList.size() == 0) loadView.loadCompleteNoData(R.mipmap.holder_no_meet_place,"暂无场地呐.....");
            }

            @Override
            public void onError(String msg) {
                if (relativeRoom.getVisibility() == View.GONE) {
                    loadView.loadCompleteNoData(R.mipmap.holder_no_meet_place,"场地预订尚未开启，请关注");
                    return;
                }
                loadView.loadComplete();
                swipeRefreshLayout.setRefreshing(false);
                meetRoomAdapter.notifyDataChangedAfterLoadMore(false);
                if (meetRoomIntroduceBeanList.size() == 0) loadView.loadCompleteNoData(R.mipmap.holder_no_meet_place,"暂无场地呐.....");
            }
        });
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(300, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                swipeRefreshLayout.setRefreshing(true);
                curPage = 1;
                getMeetList(false);
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        getMeetList(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        boolean paySuccess = intent.getBooleanExtra("paySuccess", false);
        if (paySuccess) {
            swipeRefreshLayout.setEnabled(true);
            swipeRefreshLayout.setRefreshing(true);
            onRefresh();
        }
        getOrderCanUse();
    }

    //预定记录是否有可用场次
    private void getOrderCanUse() {
        enqueue(createCallService(ServiceService.class).getOrderCanUse(DataCacheManager.getInstance().getUser().getEnterpriseAdminId()), new RetrofitCallbackListener<MeetPointResp>() {
            @Override
            public void onSuccess(Call<MeetPointResp> call, MeetPointResp result) {
                if(result.getData()==null)return;
                if ( result.getData().getOrderCanUse()==0) view_red.setVisibility(View.GONE);
                else view_red.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

}
